import React from 'react'
import { connect } from 'react-redux'
import CommonSelectDelete from 'src/pageP/common/common-select-delete'
import RefreshState from 'src/components/custom-flat-list/RefreshState'
import { cancelCollectionPost } from 'src/utils/RequestAPI'
import { CommonToast, DismissLoading, ShowLoading } from 'src/utils/ToastUtil'
import EmptyView from 'src/components/empty-view/index'
import PersonCell from 'src/components/person-cell/index'
import { findUserArchiveByUserId, operatorCenterInfo, removeArchiveCollection } from '../../../utils/RequestAPI'
import { UPDATE_MY_CENTER_NUMBERS_ACTION } from '../../main/main-page/store/action'
import { View } from 'react-native'
import { isArrayFn } from '../../../utils/JSTypeUtil'

// 发送行为
const mapDispatchToProps = dispatch => ({
  updateMyCenterNumbers (payload) {
    dispatch(UPDATE_MY_CENTER_NUMBERS_ACTION(payload))
  }
})

@connect(({ userinfo, BMineCenterStore }) => ({
  userinfoB: userinfo.B,
  haveCompanyApply: BMineCenterStore.haveCompanyApply,
  myCenterNumbers: BMineCenterStore.myCenterNumbers
}), mapDispatchToProps)
class BPersonCollection extends CommonSelectDelete {
  constructor (props) {
    super(props)
    this.state = {
      ...this.state,
      dataArr: [],
      titleNum: 0
    }
    this.titleText = '人才收藏'
    this.deleteText = '人才'
    this.page = 1
  }

  componentDidMount () {
    this.onHeaderRefresh()
  }

  generateItemChild (itemParams) {
    const { item } = itemParams
    item.education = Number(item.highestDegree)
    return (
      <PersonCell item={item}/>
    )
  }

  childItemClick (itemParams) {
    const { item } = itemParams
    this.props.navigation.navigate('CResumeDetail', {
      userId: item.userId
    })
  }

  listEmptyComponent () {
    return <EmptyView
      emptyImg={require('src/imgC/userinfo/job-collection-null.png')}
      firstTip={'无收藏人才'}
      secondTip={'快去寻找更多人才吧～'}/>
  }

  onHeaderRefresh () {
    this.page = 1
    this._operatorCenterInfo()
    this._personCollectionList(true).then((datas) => {
      this.setState(() => ({
        dataArr: datas,
        titleNum: datas.length
      }), () => {
        this.flatListRef.endRefreshing(RefreshState.NoMoreData)
        // this._refreshState(datas)
      })
    })
  }

  _operatorCenterInfo = () => {
    const { haveCompanyApply: { companyId } = {} } = this.props
    operatorCenterInfo({ headers: { companyId } }).then((result) => {
      this._setTitleNum(result.data.top.archiveCollection)
    })
  }

  _setTitleNum = (titleNum) => {
    this.setState({
      titleNum
    })
  }

  onFooterRefresh () {
    ++this.page
    this._personCollectionList().then((datas) => {
      this.setState(() => ({
        dataArr: this.state.dataArr.concat(datas)
      }), () => {
        this._refreshState(datas)
      })
    })
  }

  _personCollectionList = (showLoading) => {
    const { userinfoB } = this.props
    showLoading && ShowLoading()
    return new Promise((resolve) => {
      findUserArchiveByUserId({
        params: {
          page: this.page,
          limit: 10,
          userId: userinfoB.userId
        }
      }).then((data) => {
        showLoading && DismissLoading()
        const collections = (data && isArrayFn(data.data) && data.data.length > 0) ? data.data.map((item) => {
          item.userName = item.name
          item.comprehensive = item.comprehensive[0]
          return item
        }) : []
        console.info(collections)
        resolve(collections)
      }).catch(() => {
        showLoading && DismissLoading()
      })
    })
  }

  _refreshState = (datas) => {
    if (datas.length > 9) {
      this.flatListRef.endRefreshing(RefreshState.CanLoadMore)
    } else {
      this.flatListRef.endRefreshing(RefreshState.NoMoreData)
    }
  }

  confirmDelete () {
    ShowLoading()
    const { dataArr, checkedIndexes } = this.state
    const { userinfoB: { userId } } = this.props
    const idArr = dataArr.reduce((idArr, currentValue, index) => {
      return checkedIndexes.includes(index) ? idArr.concat(currentValue.id) : idArr
    }, [])
    removeArchiveCollection({
      params: {
        ids: idArr.join(','),
        userId: userId
      }
    }).then((data) => {
      DismissLoading()
      CommonToast(`${checkedIndexes.length}条人才收藏删除成功`)
      this._operatorCenterInfo()
      const remainData = dataArr.filter((item, index) => {
        return !checkedIndexes.includes(index)
      })
      if (remainData.length <= 0) {
        this.flatListRef.endRefreshing(RefreshState.Idle)
      }
      this.setState({
        checkedIndexes: [],
        dataArr: remainData
      })
    }).catch(() => {
      DismissLoading()
    })
  }
}

export default BPersonCollection
